import { contextBridge, ipcRenderer } from "electron";

// 定义 API 类型
interface PrimaryWindowApi {
  getCookie(params: { url: string; name: string }): Promise<string | null>;
  runAutomation(): Promise<any>;
  readExcelFile(filePath: string): Promise<any>;
}

// 创建实际的 API 对象
const primaryWindowAPI: PrimaryWindowApi = {
  getCookie: async (params: { url: string; name: string }) => {
    console.log("Preload: Calling get-cookie with params:", params);
    try {
      const result = await ipcRenderer.invoke("get-cookie", params);
      console.log("Preload: get-cookie result:", result);
      return result;
    } catch (error) {
      console.error("Preload: get-cookie error:", error);
      throw error;
    }
  },
  runAutomation: () => {
    return ipcRenderer.invoke("run-automation");
  },
  readExcelFile: (filePath: string) => {
    return ipcRenderer.invoke("read-excel-file", filePath);
  },
};

// 在预加载脚本完成时输出日志
console.log("Preload script is running");

// 暴露 API 到渲染进程
contextBridge.exposeInMainWorld("primaryWindowAPI", primaryWindowAPI);

// 确认 API 已暴露
console.log("API exposed to renderer process");

// 声明全局类型
declare global {
  interface Window {
    primaryWindowAPI: PrimaryWindowApi;
    _automationResult: any;
  }
}
